package com.feng.server.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feng.server.entiry.MessageFrame;
import com.feng.server.enums.ChatType;
import com.feng.server.service.ChatService;
import com.feng.server.service.impl.ChatServiceImpl;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private ChatService chatService = new ChatServiceImpl();

    /**
     * 每当从客户端有消息写入时
     *
     * @param channelHandlerContext
     * @param textWebSocketFrame
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        Channel inComing = channelHandlerContext.channel();
        String msg = textWebSocketFrame.text();

        try {
            JSONObject msgFrame = JSON.parseObject(msg);
            System.out.println("服务端收到消息：\t" + msgFrame.toJSONString());
            MessageFrame messageFrame = JSON.parseObject(msg, MessageFrame.class);
            handlemessageFrame(inComing, messageFrame);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void handlemessageFrame(Channel inComing, MessageFrame messageFrame) {
        ChatType chatType = messageFrame.getChatType();
        switch (chatType) {
            case SINGLE_SENDING:
                chatService.singleSend(messageFrame);
                break;
            case CONNECTED:
                chatService.saveConnectedSession(inComing, messageFrame);
        }
    }

    /**
     * 当服务器监听到客户端活动时
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel inComing = ctx.channel();
        System.out.println("[" + inComing.remoteAddress() + "]: 在线");
        //todo 向客户端推送未读消息
    }

    /**
     * 离线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel inComing = ctx.channel();
        System.out.println("[" + inComing.remoteAddress() + "]: 离线");

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel inComing = ctx.channel();
        cause.printStackTrace();
        System.out.println(inComing.remoteAddress() + "通讯异常！");
        ctx.close();
    }


}
